package com.xuanwoa.rabbit.delay.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * Description
 *
 * @author: xuanwoa
 * @since: 2020/11/15
 */
@RestController
@RequestMapping("delay")
@Slf4j
public class DelayController {

    private final Queue queue = new ArrayDeque();

    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping("send")
    public String send(@RequestParam String msg, @RequestParam Integer delay) {
        amqpTemplate.convertAndSend("delay.exchange","delayqueue", msg, message -> {
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            message.getMessageProperties().setDelay(delay * 1000);
            return message;
        });
        return msg + ":" + delay;
    }

    @RabbitListener(id = "b",queues = "delayqueue")
    public void receive(String msg) {
        log.info("received delay msg {}",msg);
        queue.offer(msg);
    }

    @GetMapping("receive")
    public String receive() {
        return String.valueOf(queue.poll());
    }
}
